package com.duolaibei.business.view.goods;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.business.R;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.SysUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.view.goods.mode.FormatsBean;
import com.duolaibei.business.view.goods.mode.FormatsBeanManager;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.NestedRecyclerView;
import com.library.flowlayout.SpaceItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Created by Administrator on 2018/9/28.
 */

public class FormatsActiviy extends BaseActivity {

    @Inject(R.id.back)
    private RelativeLayout mBack;
    @Inject(R.id.title)
    private TextView mTitle;
    @Inject(R.id.btn_formats_edit)
    private TextView mTxtFormatsEdit;
    @Inject(R.id.recycle_formats)
    private RecyclerView mRecycleFormats;
    @Inject(R.id.btn_formats_add)
    private TextView mTxtFormatAdd;

    private FormatsAdapter mFormatsAdapter;

    private List<FormatsBean> mFormatsList = new ArrayList<>();

    //    private int countFormat = 0;
    private HashSet<Integer> hashSet = new HashSet<>();

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_formats_manage);
    }

    @Override
    protected void initViews() {
        mTitle.setText("选择规格");
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setFormatsAdapter();
        initFormatsData();
    }

    @Override
    protected void onSetListener() {
        mBack.setOnClickListener(getThis());
        mTxtFormatsEdit.setOnClickListener(getThis());
        mTxtFormatAdd.setOnClickListener(getThis());
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back) {
            finish();
        } else if (v.getId() == R.id.btn_formats_edit) {
            savaFormat();
        } else if (v.getId() == R.id.btn_formats_add) {
            addFormatName();
        }
    }

    @Override
    protected void afterBackPressed() {
        super.afterBackPressed();
        finish();
    }

    @Override
    public void finish() {
        deleteAllChecked();
        super.finish();
    }

    /**
     * 清理所有选中状态，保存数据
     */
    private void deleteAllChecked() {
//        for (FormatsBean dataBean : mFormatsList) {
//            dataBean.setChoosed(false);
//            for (FormatsBean.DataBean dataBean1 : dataBean.getData()) {
//                if (!"-1".equals(dataBean1.getState())) {
//                    dataBean1.setState("0");
//                }
//            }
//            FormatsBeanManager.getInstance().updateFormats(dataBean);
//        }
        mRecycleFormats.destroyDrawingCache();
    }

    private void initFormatsData() {
        List list = FormatsBeanManager.getInstance().selectAllFormats();
        mFormatsList.clear();
        mFormatsList.addAll(list);
        for (FormatsBean formatsBean : mFormatsList) {
            if (formatsBean.getIsChoosed()) {
                List<FormatsBean.DataBean> list1 = formatsBean.getData();
                for (int j = 0; j < list1.size(); j++) {
                    String state = list1.get(j).getState();
                    if ("1".equals(state)) {
                        hashSet.add(formatsBean.getFormatNum());
                    }
                }
            }
        }
        mFormatsAdapter.notifyDataSetChanged();
    }

    private void setFormatsAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getThis());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycleFormats.setLayoutManager(layoutManager);
        mRecycleFormats.setFocusableInTouchMode(false);
        mRecycleFormats.setItemViewCacheSize(0);
        Drawable drawable = ContextCompat.getDrawable(Objects.requireNonNull(getThis()), R.drawable.shape_recycle_div);
        DividerItemDecoration decoration = new DividerItemDecoration(Objects.requireNonNull(getThis()), DividerItemDecoration.VERTICAL);
        if (drawable != null) {
            decoration.setDrawable(drawable);
            mRecycleFormats.addItemDecoration(decoration);
        }/* else
            mRecycleFormats.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getThis()), DividerItemDecoration.VERTICAL));*/
        mFormatsAdapter = new FormatsAdapter(getThis(), R.layout.item_formats_manage, mFormatsList);
        mRecycleFormats.setAdapter(mFormatsAdapter);
    }

    private class FormatsAdapter extends CommonAdapter<FormatsBean> {

        public FormatsAdapter(Context context, int layoutId, List<FormatsBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final FormatsBean formatsBean, final int position) {
            holder.setIsRecyclable(false);
            holder.setText(R.id.format_name, formatsBean.getTitle());
            boolean isShow = formatsBean.isChoosed();
            LinearLayout view = holder.getView(R.id.format_edit);
            if (isShow) {
                holder.getView(R.id.format_name).setBackground(new ColorDrawable(Color.parseColor("#e6e6e6")));
                view.setVisibility(View.VISIBLE);
            } else {
                holder.getView(R.id.format_name).setBackground(new ColorDrawable(Color.parseColor("#ffffff")));
                view.setVisibility(View.GONE);
            }
            NestedRecyclerView nestedRecyclerView = holder.getView(R.id.recycle_format_name);
            nestedRecyclerView.setNestedScrollingEnabled(false);
            nestedRecyclerView.setItemViewCacheSize(0);
            if (nestedRecyclerView.getAdapter() == null) {
                FlowAdapter flowAdapter = new FlowAdapter(getThis(), R.layout.flow_item, formatsBean.getData(), formatsBean);
                FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
                nestedRecyclerView.setLayoutManager(flowLayoutManager);
                nestedRecyclerView.addItemDecoration(new SpaceItemDecoration(dp2px(6)));
                nestedRecyclerView.setAdapter(flowAdapter);
            } else {
                nestedRecyclerView.getAdapter().notifyDataSetChanged();
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setCheckState(formatsBean);
                }
            });
        }

        private int dp2px(float value) {
            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getThis().getResources().getDisplayMetrics());
        }

        private class FlowAdapter extends CommonAdapter<FormatsBean.DataBean> {

            private FormatsBean formatsBean;

            public FlowAdapter(Context context, int layoutId, List<FormatsBean.DataBean> datas, FormatsBean formatsBean) {
                super(context, layoutId, datas);
                this.formatsBean = formatsBean;
            }

            @Override
            protected void convert(final ViewHolder holder, final FormatsBean.DataBean dataBean, final int position) {
                holder.setIsRecyclable(false);
                TextView textView = holder.getView(R.id.flow_text);
                textView.setText(dataBean.getName());
                String state = dataBean.getState();
                if ("0".equals(state)) {
                    textView.setBackground(getResources().getDrawable(R.drawable.product_item_back));
                } else if ("1".equals(state)) {
                    textView.setBackground(getResources().getDrawable(R.drawable.product_item_select_back));
                } else if ("-1".equals(state)) {
                    textView.setBackground(getResources().getDrawable(R.drawable.product_item_select_back));
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String state = dataBean.getState();
                        if ("-1".equals(state)) {
                            addFormat(formatsBean, position);
                        } else
                            setFormatCheckState(formatsBean, position);
                    }
                });
            }
        }

        /**
         * 设置规格值点击状态
         *
         * @param formatsBean
         * @param position
         */
        private void setFormatCheckState(FormatsBean formatsBean, int position) {
            for (int i = 0; i < mFormatsList.size(); i++) {
                if (formatsBean.getFormatNum() == mFormatsList.get(i).getFormatNum()) {
                    for (int j = 0; j < formatsBean.getData().size(); j++) {
                        String state = formatsBean.getData().get(position).getState();
                        if (position == j) {
                            if ("0".equals(state)) {
                                formatsBean.getData().get(position).setState("1");
                                hashSet.add(mFormatsList.get(i).getFormatNum());
                            } else if ("1".equals(state)) {
                                formatsBean.getData().get(position).setState("0");
                                hashSet.remove(mFormatsList.get(i).getFormatNum());
                            }
                        }
                    }
                }
            }
            mFormatsAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 设置Item的点击状态
     *
     * @param formatsBean
     */
    private void setCheckState(FormatsBean formatsBean) {
        if (hashSet.size() >= 3) {
            if (!hashSet.contains(formatsBean.getFormatNum())) {
                showToast("最多可以选择3个规格");
                return;
            }
        }
        for (int i = 0; i < mFormatsList.size(); i++) {
            if (formatsBean.getFormatNum() == mFormatsList.get(i).getFormatNum()) {
                if (formatsBean.getIsChoosed()) {
                    for (FormatsBean.DataBean dataBean : formatsBean.getData()) {
                        if (!"-1".equals(dataBean.getState())) {
                            dataBean.setState("0");
                        }
                    }
                    formatsBean.setChoosed(false);
                    hashSet.remove(formatsBean.getFormatNum());
                } else {
                    formatsBean.setChoosed(true);
                }
            } else {
                FormatsBean formatBean = mFormatsList.get(i);
                Set<String> stringSet = new HashSet<>();
                for (FormatsBean.DataBean dataBean : formatBean.getData()) {
                    stringSet.add(dataBean.getState());
                }
                if (stringSet.contains("1")) {
                    formatBean.setChoosed(true);
                    hashSet.add(formatBean.getFormatNum());
                } else {
                    formatBean.setChoosed(false);
                    hashSet.remove(formatBean.getFormatNum());
                }
            }
        }
        mFormatsAdapter.notifyDataSetChanged();
    }


    /**
     * 编辑类型按钮
     */
    private void savaFormat() {
        if (hashSet.size() == 0) {
            showToast("请至少选择一个规格");
            return;
        }
        Intent intent = new Intent();
        List<FormatsBean> list = new ArrayList<>();
        for (FormatsBean formatsBean : mFormatsList) {
            if (hashSet.contains(formatsBean.getFormatNum())) {
                formatsBean.setChoosed(true);
                list.add(formatsBean);
            } else {
                formatsBean.setChoosed(false);
            }
            FormatsBeanManager.getInstance().updateFormats(formatsBean);
        }
        intent.putExtra("format_checked", (Serializable) list);
        setResult(RESULT_OK, intent);
        finish();
    }


    /**
     * 增加新的类型
     */
    @SuppressLint("RestrictedApi")
    private void addFormat(final FormatsBean formatsBean, final int position) {
        //判断类型是否重复
        AlertDialog.Builder builder = new AlertDialog.Builder(getThis());
        builder.setTitle("添加规格");
        final EditText editText = new EditText(getThis());
        editText.setTextSize(15);
        editText.setHint("请输入规格值");
        builder.setView(editText, 60, 40, 60, 40);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                SysUtil.hideSoftInput(editText);
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String content = editText.getText().toString();
                if (CommonUtil.isEmpty(content)) {
                    showToast("规格值不能为空");
                    return;
                }
                List<FormatsBean.DataBean> list = formatsBean.getData();
                for (FormatsBean.DataBean dataBean1 : list) {
                    if (content.equals(dataBean1.getName())) {
                        showToast("名称不能重复");
                        return;
                    }
                }
                FormatsBean.DataBean dataBean = new FormatsBean.DataBean();
                dataBean.setName(content);
                dataBean.setState("1");
                Collections.reverse(list);
                list.add(dataBean);
                Collections.reverse(list);
                formatsBean.setData(list);
                hashSet.add(formatsBean.getFormatNum());
                mFormatsAdapter.notifyDataSetChanged();
            }
        });
        builder.show();
        SysUtil.showSoftInput(editText);
    }


    /**
     * 增加新的类型
     */
    @SuppressLint("RestrictedApi")
    private void addFormatName() {
        //判断类型是否重复
        AlertDialog.Builder builder = new AlertDialog.Builder(getThis());
        builder.setTitle("添加规格");
        final EditText editText = new EditText(getThis());
        editText.setTextSize(15);
        editText.setHint("请输入规格名称");
        builder.setView(editText, 60, 40, 60, 40);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                SysUtil.hideSoftInput(editText);
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FormatsBean formatsBean = new FormatsBean();
                String content = editText.getText().toString();
                formatsBean.setTitle(content);
                formatsBean.setChoosed(false);
                formatsBean.setFormatNum(Integer.parseInt(getRadomInt()));
                FormatsBean.DataBean dataBean;
                List<FormatsBean.DataBean> list = new ArrayList<>();
                dataBean = new FormatsBean.DataBean();
                dataBean.setName("添加规格");
                dataBean.setState("-1");
                list.add(dataBean);
                formatsBean.setData(list);
                if (isRepeatFormat(formatsBean)) {
                    return;
                }
                mFormatsList.add(formatsBean);
                mFormatsAdapter.notifyItemInserted(mFormatsList.size() + 1);
                FormatsBeanManager.getInstance().addFormats(formatsBean);
            }
        });
        builder.show();
        SysUtil.showSoftInput(editText);
    }

    /**
     * 判断是否重复
     *
     * @param FormatsBean
     * @return
     */
    private boolean isRepeatFormat(FormatsBean FormatsBean) {
        List<FormatsBean> list = FormatsBeanManager.getInstance().selectAllFormats();
        for (FormatsBean FormatsBean1 : list) {
            if (FormatsBean1.getTitle().endsWith(FormatsBean.getTitle())) {
                showToast("名称不能重复");
                return true;
            }
        }
        return false;
    }

    /**
     * 获取五位数随机数
     *
     * @return
     */
    private String getRadomInt() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            int a = (int) (Math.random() * 9) + 1;
            buffer.append(String.valueOf(a));
        }
        return buffer.toString();
    }
}
